<template>
  <view class="apply-withdraw-container">

    <!-- 表单区域 -->
    <view class="form-section">
      <!-- 账户余额 -->
      <view class="balance-info">
        <text class="balance-label">账户余额</text>
        <text class="balance-amount">¥{{ currentBalance.toFixed(2) }}</text>
      </view>

      <!-- 提现金额 -->
      <view class="form-item">
        <text class="form-label">提现金额</text>
        <view class="input-container">
          <input 
            type="digit" 
            v-model="withdrawAmount" 
            placeholder="请输入提现金额"
            class="form-input"
          />
          <text class="input-suffix">元</text>
        </view>
      </view>

      <!-- 真实姓名 -->
      <view class="form-item">
        <text class="form-label">真实姓名</text>
        <input 
          type="text" 
          v-model="realName" 
          placeholder="请输入真实姓名"
          class="form-input"
        />
      </view>

      <!-- 选择银行 -->
      <view class="form-item">
        <text class="form-label">请选择银行</text>
        <picker @change="bindPickerChange" :range="bankList" range-key="name">
          <view class="picker-content">
            {{ selectedBank || '请选择银行' }}
            <text class="picker-arrow">▼</text>
          </view>
        </picker>
      </view>

      <!-- 银行卡号 -->
      <view class="form-item">
        <text class="form-label">请输入银行卡卡号</text>
        <input 
          type="text" 
          v-model="bankCardNumber" 
          placeholder="请输入银行卡卡号"
          class="form-input"
          maxlength="19"
          @input="formatBankCard"
        />
      </view>

      <!-- 提示信息 -->
      <text class="notice-text">xxx不会通过任何渠道泄露您的个人信息，请放心填写</text>

      <!-- 确认按钮 -->
      <button class="submit-btn" @click="submitApplication">确认信息并提交</button>
    </view>

    <!-- 提现记录 -->
    <view class="record-section">
      <text class="section-title">提现记录</text>
      
      <view class="record-list">
        <view 
          v-for="(record, index) in withdrawalRecords" 
          :key="index"
          class="record-item"
        >
          <view class="record-info">
            <text class="record-type">{{ record.type }}</text>
            <text class="record-time">{{ record.time }}</text>
          </view>
          <view class="record-status">
            <text class="record-amount">{{ record.amount }}</text>
            <text :class="['record-status-text', record.statusClass]">{{ record.status }}</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script lang="ts">
import { defineComponent, ref, onMounted } from 'vue';
import request from '@/utils/request';

export default defineComponent({
  name: 'ApplyWithdraw',
  setup() {
    // 响应式数据
    const withdrawAmount = ref('');
    const realName = ref('');
    const bankCardNumber = ref('');
    const selectedBank = ref('');
    const currentBalance = ref(1500); // 默认值，将从参数中更新
    
    // 银行列表
    const bankList = ref([
      { id: 1, name: '中国工商银行' },
      { id: 2, name: '中国建设银行' },
      { id: 3, name: '中国农业银行' },
      { id: 4, name: '中国银行' },
      { id: 5, name: '中国邮政储蓄银行' },
      { id: 6, name: '招商银行' },
      { id: 7, name: '交通银行' },
      { id: 8, name: '中信银行' },
    ]);

    // 提现记录
    const withdrawalRecords = ref([]);
    
    // 在组件挂载时获取传递的参数
    onMounted(() => {
      // 获取导航参数
      const pages = getCurrentPages();
      // 使用类型断言来解决TypeScript类型错误
      const currentPage = pages[pages.length - 1] as any;
      const options = currentPage.options || {};
      
      // 更新当前余额
      if (options.currentBalance) {
        currentBalance.value = parseFloat(options.currentBalance);
      }
      
      // 更新提现记录
      if (options.withdrawRecords) {
        try {
          const records = JSON.parse(decodeURIComponent(options.withdrawRecords));
          if (Array.isArray(records) && records.length > 0) {
            // 将WithdrawRecord格式转换为withdrawalRecords格式
            withdrawalRecords.value = records.map(record => ({
              type: '商家提现申请',
              time: record.withdrawalRecord || record.updateTime || new Date().toLocaleString(),
              amount: '-' + (typeof record.cashWithdrawal === 'number' ? record.cashWithdrawal.toFixed(2) : String(record.cashWithdrawal || '0.00')),
              status: getStatusText(record.status),
              statusClass: getStatusClass(record.status)
            }));
          }
        } catch (error) {
          console.error('解析提现记录失败:', error);
        }
      }
    });
    
    // 根据状态码获取状态文本
    const getStatusText = (status: string | number | null | undefined): string => {
      // 将数字类型转换为字符串进行统一处理
      const statusStr = String(status);
      switch (statusStr) {
        case '0':
        case 'pending':
          return '审核中';
        case '1':
        case 'approved':
          return '审核通过';
        case '2':
        case 'rejected':
          return '审核不通过';
        default:
          return '审核中';
      }
    };
    
    // 根据状态码获取状态样式类
    const getStatusClass = (status: string | number | null | undefined): string => {
      // 将数字类型转换为字符串进行统一处理
      const statusStr = String(status);
      switch (statusStr) {
        case '0':
        case 'pending':
          return 'status-pending';
        case '1':
        case 'approved':
          return 'status-approved';
        case '2':
        case 'rejected':
          return 'status-rejected';
        default:
          return 'status-pending';
      }
    };

    // 处理返回
    const handleBack = () => {
      uni.navigateBack();
    };

    // 银行选择
    const bindPickerChange = (e: any) => {
      const index = e.detail.value;
      selectedBank.value = bankList.value[index].name;
    };

    // 格式化银行卡号（每4位加空格）
    const formatBankCard = (e: any) => {
      let value = e.target.value.replace(/\s/g, '');
      const formattedValue = value.replace(/(\d{4})/g, '$1 ').trim();
      bankCardNumber.value = formattedValue;
    };

    // 提交申请
    const submitApplication = async () => {
      // 表单验证
      if (!withdrawAmount.value || parseFloat(withdrawAmount.value) <= 0) {
        uni.showToast({ title: '请输入有效的提现金额', icon: 'none' });
        return;
      }
      
      if (parseFloat(withdrawAmount.value) > currentBalance.value) {
        uni.showToast({ title: '提现金额不能超过账户余额', icon: 'none' });
        return;
      }
      
      if (!realName.value.trim()) {
        uni.showToast({ title: '请输入真实姓名', icon: 'none' });
        return;
      }
      
      if (!selectedBank.value) {
        uni.showToast({ title: '请选择银行', icon: 'none' });
        return;
      }
      
      if (!bankCardNumber.value.trim()) {
        uni.showToast({ title: '请输入银行卡卡号', icon: 'none' });
        return;
      }

      try {
        // 调用新增提现记录接口
        const response = await request({
          url: "/wsy/withdrawal",
          method: "POST",
          data: {
            merchantId: 2, // 商家ID
            currentBalance: currentBalance.value,
            cashWithdrawal: parseFloat(withdrawAmount.value),
            realName: realName.value.trim(),
            bankCardNumber: bankCardNumber.value.trim()
          }
        });

        // 检查响应是否成功
        if (response > 0) {
          // 提交成功后跳转到成功页面
          uni.navigateTo({
            url: '/pages/income/withdrawSuccess',
            success: () => {
              // 重置表单
              withdrawAmount.value = '';
              realName.value = '';
              bankCardNumber.value = '';
              selectedBank.value = '';
            }
          });
        } else {
          uni.showToast({ title: '提交失败，请重试', icon: 'none' });
        }
      } catch (error) {
        console.error('提交提现申请失败:', error);
        uni.showToast({ title: '网络异常，请稍后重试', icon: 'none' });
      }
    };

    return {
      withdrawAmount,
      realName,
      bankCardNumber,
      selectedBank,
      bankList,
      withdrawalRecords,
      currentBalance,
      handleBack,
      bindPickerChange,
      formatBankCard,
      submitApplication
    };
  }
});
</script>

<style scoped>
.apply-withdraw-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-top: 40rpx; /* 给整个页面添加顶部内边距 */
}

/* 头部导航 */
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 100rpx;
  background-color: #ffffff;
  padding: 0 30rpx;
  border-bottom: 1rpx solid #e5e5e5;
}

.header-left,
.header-right {
  width: 60rpx;
}

.back-icon {
  font-size: 40rpx;
  color: #333333;
}

.header-title {
  font-size: 36rpx;
  font-weight: 500;
  color: #333333;
}

/* 表单区域 */
.form-section {
  background-color: #ffffff;
  margin: 20rpx 0;
  padding: 30rpx;
  padding-top: 80rpx; /* 增加顶部内边距，防止被状态栏挡住 */
}

.balance-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 40rpx;
}

.balance-label {
  font-size: 32rpx;
  color: #666666;
}

.balance-amount {
  font-size: 40rpx;
  font-weight: 600;
  color: #ff6b00;
}

.status-pending {
  color: #ffa500;
}

.status-approved {
  color: #52c41a;
}

.status-rejected {
  color: #f5222d;
}

.form-item {
  display: flex;
  flex-direction: column;
  margin-bottom: 30rpx;
}

.form-label {
  font-size: 28rpx;
  color: #666666;
  margin-bottom: 10rpx;
}

.input-container {
  display: flex;
  align-items: center;
}

.form-input {
  flex: 1;
  height: 80rpx;
  font-size: 32rpx;
  color: #333333;
  border-bottom: 1rpx solid #e5e5e5;
  padding: 0;
}

.input-suffix {
  font-size: 32rpx;
  color: #999999;
  margin-left: 10rpx;
}

.picker-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 80rpx;
  font-size: 32rpx;
  color: #999999;
  border-bottom: 1rpx solid #e5e5e5;
}

.picker-arrow {
  font-size: 24rpx;
  color: #999999;
}

.notice-text {
  display: block;
  font-size: 24rpx;
  color: #999999;
  margin: 30rpx 0;
}

.submit-btn {
  width: 100%;
  height: 88rpx;
  line-height: 88rpx;
  background-color: #1989fa;
  color: #ffffff;
  font-size: 32rpx;
  border-radius: 44rpx;
  margin-top: 20rpx;
  border: none;
}

.submit-btn::after {
  border: none;
}

/* 提现记录 */
.record-section {
  background-color: #ffffff;
  padding: 30rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: 500;
  color: #333333;
  margin-bottom: 20rpx;
}

.record-item {
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f5f5f5;
}

.record-item:last-child {
  border-bottom: none;
}

.record-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10rpx;
}

.record-type {
  font-size: 30rpx;
  color: #333333;
}

.record-time {
  font-size: 26rpx;
  color: #999999;
}

.record-status {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.record-amount {
  font-size: 32rpx;
  font-weight: 500;
  color: #ff6b00;
}

.record-status-text {
  font-size: 28rpx;
}

.status-pending {
  color: #ff9500;
}

.status-approved {
  color: #52c41a;
}

.status-rejected {
  color: #ff4d4f;
}
</style>